<template>
  <div class="login">
    <router-link to="/">
      <img
        src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2F7d%2Fe8%2F80%2F7de8803ad970bf28bbbe94ff22b52528.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664763079&t=72ab61c10baaec1039a4713935ff45d7"
        class="logo"
        alt=""
      />
    </router-link>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userName"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
    <router-link :to="{ name: 'Reg' }">没有账号，我要注册</router-link>
  </div>
</template>

<script>
import { setToken } from "../utils/auth";
import { loginAPI } from "../service/auth";
import { Notify } from "vant";
export default {
  data() {
    return {
      userName: "",
      password: "",
    };
  },
  methods: {
    async onSubmit() {
      const res = await loginAPI({
        userName: this.userName,
        password: this.password,
      });
      if (res.code == 1) {
        Notify({
          type: "success",
          message: "登录成功",
        });
        // 存数据
        setToken(res.data);
        // dispatch 派发一个action 获取购物车信息
        this.$store.dispatch("loadCarts");
        // 跳转到个人中心
        this.$router.replace({
          name: "User",
        });
      } else {
        Notify({
          type: "warning",
          message: res.data,
        });
      }
    },
  },
};
</script>

<style scoped>
.logo {
  width: 45vw;
  display: block;
  margin: 20px auto;
  border-radius: 16px;
}
</style>
